package leetcode.editor.day;

// 1592. 重新排列单词间的空格
// https://leetcode.cn/problems/rearrange-spaces-between-words/
class RearrangeSpacesBetweenWords {
    public static void main(String[] args) {
        Solution solution = new RearrangeSpacesBetweenWords().new Solution();
//        solution.reorderSpaces("  this   is  a sentence ");
        solution.reorderSpaces("  hello");
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        // 直接模拟，只不过代码不够优化
        public String reorderSpaces(String text) {
            int n = text.length();
            int count = 0;
            for (int i = 0; i < n; i++) {
                if (text.charAt(i) == ' ') count++;
            }

            if (count == 0) return text;

            String[] arr = text.trim().split(" ");
            int count1 = 0;
            for (String s : arr) {
                if (s.length() != 0) count1++;
            }

            StringBuilder sb = new StringBuilder();
            if (count1 == 1) {
                sb.append(text.trim());
                for (int i = 0; i < count; i++) {
                    sb.append(" ");
                }
            } else {
                int count2 = count / (count1 - 1), count3 = count % (count1 - 1);
                for (int i = 0; i < arr.length; i++) {
                    if (arr[i].length() != 0) {
                        sb.append(arr[i]);
                        if (i != arr.length - 1)
                            for (int j = 0; j < count2; j++) sb.append(" ");
                    }
                }

                for (int i = 0; i < count3; i++) {
                    sb.append(" ");
                }
            }
            return sb.toString();
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
